package com.microservice.auth.jwt.point;

import cn.hutool.json.JSONUtil;
import com.microservice.core.domain.AjaxResult;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * AuthenticationEntryPoint 是 Spring Security 中的一个接口，用于处理未认证用户的访问请求。当一个未认证的用户尝试访问受保护的资源时，
 * Spring Security 会调用 AuthenticationEntryPoint 来处理这种情况，通常用于启动身份验证过程或返回未授权的响应
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException {

        httpServletResponse.setContentType("application/json;charset=UTF-8");
        httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        AjaxResult ajaxResult = AjaxResult.error("请先登录");

        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(ajaxResult).getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
